<template>
  <div class="search-container">
    <!-- 搜索栏 -->
    <form action="/" class="search-from">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
        @input="onChange"
        background="#3296fa"
      />
    </form>
    <!-- 搜索结果 -->
    <search-result
      v-if="isResultShow"
      :search-text="searchText"
    ></search-result>
    <!-- /搜索结果 -->

    <!-- 联想建议 -->
    <search-suggestion
      v-else-if="searchText"
      :search-text="searchText"
      @search="onSearch"
    ></search-suggestion>
    <!-- /联想建议 -->

    <!-- 搜索历史记录 -->
    <search-history
      v-else
      :search-histories="SearchHistories"
      @search="onSearch"
      @clear-search-history="SearchHistories = []"
    ></search-history>
    <!-- /搜索历史记录 -->
  </div>
</template>

<script>
import SearchHistory from '@/components/SearchHistory.vue';
import SearchSuggestion from '@/components/SearchSuggestion.vue';
import SearchResult from '@/components/SearchResult.vue';
import { setItem, getItem } from '@/plugins/storage.js';
export default {
  name: 'SearchIndex',
  data() {
    return {
      searchText: '',
      isResultShow: false, // 搜索结果的展示
      SearchHistories: getItem('TOUTIAO_SEARCH_HISTORIES') || [], // 搜索的历史记录
    };
  },
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult,
  },
  watch: {
    SearchHistories(value) {
      setItem('TOUTIAO_SEARCH_HISTORIES', value);
    },
  },
  methods: {
    onChange(val) {
      if (val === '') {
        this.isResultShow = false;
      }
    },
    onSearch(val) {
      this.searchText = val;
      const a = this.SearchHistories.indexOf(val);
      if (a !== -1) {
        this.SearchHistories.splice(a, 1);
      }
      this.SearchHistories.unshift(val);
      this.isResultShow = true;
    },
    onCancel() {
      this.$router.back();
    },
  },
};
</script>

<style lang="less" scoped>
.search-container {
  padding-top: 107px;
  .van-search__action {
    color: #fff;
  }
  .van-search__action:active {
    background-color: transparent;
  }
  .search-from {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
}
</style>
